# -*- coding:utf-8 -*-
# TODO
# post cmt slow
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import json, time, sys, os, sets, logging
os.sys.path.append('../utils/constants/')
from constants import *
os.sys.path.append('../utils/memcacheDao/')
import memcacheDao
os.sys.path.append('../modules/antispam/')
import antispam
os.sys.path.append('../modules/comment/')
import commentLogic
os.sys.path.append('../modules/user/')
import userLogic
os.sys.path.append('../modules/discuss/')
import discussLogic
os.sys.path.append('../modules/message/')
import messageLogic

from tornado.options import define, options
reload(sys)  
sys.setdefaultencoding("utf-8")  


class DiscussHandler(tornado.web.RequestHandler):
    def get(self):
        mc = memcacheDao.memcacheDao()
        strType = self.get_argument('type')
        #print self.get_argument('field')
        ret = {}
        #print strType
        if strType == 'list':
            # 获取列表
            field  = self.get_argument('field', 'last_reply_time')
            pageno = int(self.get_argument('pageno', 0))
            if field not in sets.Set(['last_reply_time', 'pv_count', 'creat_time', 'comm_count',]):
                field = 'last_reply_time'
            discuss_logic = discussLogic.discussLogic(self.application.db, mc.getInstance())
            ret = discuss_logic.order_by(field, pageno)
            logging.info('t:%s r:%u f:%s p:%u' % (strType, ret['retcode'], field, pageno,))
        elif strType == 'discuss':
            # 获取详细
            discuss_id = int(self.get_argument('discuss_id'))
            uip = self.request.remote_ip
            discuss_logic = discussLogic.discussLogic(self.application.db, mc.getInstance())
            ret = discuss_logic.get_discuss(discuss_id, uip)
            logging.info('t:%s r:%u id:%u' % (strType, ret['retcode'], discuss_id,))
        elif strType == 'comment':
            discuss_id = int(self.get_argument('discuss_id'))
            pageno = int(self.get_argument('pageno', 0))
            discuss_logic = discussLogic.discussLogic(self.application.db, mc.getInstance())
            ret = discuss_logic.get_comment(discuss_id, pageno)
            logging.info('t:%s r:%u id:%u p:%u' % (strType, ret['retcode'], discuss_id, pageno,))
        else:
            # 404
            ret['retcode'] = E_METHOD_NOT_EXIST
            ret['message'] = 'method not exists'
            logging.warning('t:%s method not exists' % (strType,))
        self.write(json.dumps(ret))

    def post(self):
        mc = memcacheDao.memcacheDao()
        strType = self.get_argument('type')
        argument_dict = {}
        ret = {}
        user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
        string_base64 = self.get_argument('code', '')
        checkin_ret = user_logic.checkin(string_base64)
        if strType == 'post_discuss':
            if checkin_ret['retcode'] != 0:
                ret = checkin_ret
                logging.warning('t:%s chk:%u' % (strType, ret['retcode'],))
            else:
                anti = antispam.antispam(mc.getInstance())
                anti_item = {}
                anti_item['uip']     = self.request.remote_ip
                anti_item['content'] = self.get_argument('title')
                anti_item['user_id'] = checkin_ret['retbody']['user_id']
                anti_ret = anti.check_repeat(anti_item)
                if anti_ret['retcode'] != 0:
                    ret = anti_ret
                    logging.info('t:%s anti:%u uid:%u uip:%s' % (strType, ret['retcode'], \
                            anti_item['user_id'], anti_item['uip']))
                else:
                    discuss_item = {}
                    #['title', 'content', 'uip', 'discuss_uid', 'discuss_uname', 'creat_time', 'last_reply_time',]
                    discuss_item['title']           = self.get_argument('title').encode('utf8')
                    discuss_item['content']         = self.get_argument('content').encode('utf8')
                    discuss_item['uip']             = self.request.remote_ip
                    discuss_item['sex']             = int(checkin_ret['retbody']['sex']) 
                    discuss_item['age']             = int(time.strftime("%Y")) - checkin_ret['retbody']['birth_year']
                    discuss_item['discuss_uid']     = checkin_ret['retbody']['user_id']
                    discuss_item['discuss_uname']   = checkin_ret['retbody']['user_name']
                    #print checkin_ret['retbody']['user_name']
                    discuss_item['creat_time']      = int(time.time())
                    discuss_item['last_reply_time'] = discuss_item['creat_time']
                    discuss_logic = discussLogic.discussLogic(self.application.db, mc.getInstance())
                    ret = discuss_logic.add(discuss_item)
                    if ret['retcode'] == 0:
                        # 给用户加活跃值
                        user_logic.bonus4post_thread(checkin_ret['retbody']['user_id'])
                        anti.set_content(anti_item)
                    logging.info('t:%s r:%u uid:%u un:%s sex:%u age:%u ip:%s' % (strType, ret['retcode'], \
                            discuss_item['discuss_uid'],discuss_item['discuss_uname'], \
                            discuss_item['sex'], discuss_item['age'], discuss_item['uip'],))

        elif strType == 'ding_discuss':
            #argument_dict = self.get_checkin_argument()
            discuss_logic = discussLogic.discussLogic(self.application.db, mc.getInstance())
            ding_item = {}
            ding_item['ding'] = 1
            ding_item['uip'] = self.request.remote_ip
            ding_item['discuss_id'] = int(self.get_argument('id'))
            discuss_uid = int(self.get_argument('uid'))
            ret = discuss_logic.ding(ding_item)
            logmsg = 't:%s r:%u id:%u ip:%s uid:%u' % (strType, ret['retcode'], ding_item['discuss_id'], \
                    ding_item['uip'], discuss_uid,)
            if 0 == ret['retcode']:
                # 给用户加活跃值
                if checkin_ret['retcode'] == 0:
                    user_logic.bonus4ding(checkin_ret['retbody']['user_id'])
                    logmsg += ' ding:%u' % (checkin_ret['retbody']['user_id'],)
                # 给被顶用户增加声望值
                user_logic.bonus4dinged(discuss_uid)
                # TODO 要不要发消息呢
            logging.info(logmsg)
            
        elif strType == 'ding_cmt':
            #argument_dict = self.get_register_argument()
            discuss_logic = discussLogic.discussLogic(self.application.db, mc.getInstance())
            ding_item = {}
            ding_item['uip'] = self.request.remote_ip
            ding_item['thread_id']       = int(self.get_argument('id'))
            ding_item['comment_id']      = int(self.get_argument('cmt_id'))
            comment_uid = int(self.get_argument('cmt_uid'))
            ret = discuss_logic.ding_comment(ding_item)
            logmsg = 't:%s r:%u chk:%u id:%u cid:%u cuid:%u ip:%s' % (strType, ret['retcode'], checkin_ret['retcode'], \
                    ding_item['thread_id'], ding_item['comment_id'], comment_uid, ding_item['uip'],)
            #print ret, checkin_ret
            if ret['retcode'] == 0 and checkin_ret['retcode'] == 0:
                # 给用户加活跃值
                user_logic.bonus4ding(checkin_ret['retbody']['user_id'])
                # 给被顶用户增加声望值
                user_logic.bonus4dinged(comment_uid)
                # 发信通知
                message_item = {}
                message_item['recv_uid']   = comment_uid
                message_item['send_uid']   = checkin_ret['retbody']['user_id']
                message_item['send_uname'] = checkin_ret['retbody']['user_name']
                message_item['itype']      = T_DISCUSS_COMMENT_DING
                message_item['creat_time'] = int(time.time())

                content = {}
                # $send_uname 喜欢你在 $thread_id 中的评论: $comment_content
                content['id']    = ding_item['thread_id']
                content['cmt']   = self.get_argument('cmt')
                content['sex']   = checkin_ret['retbody']['sex']
                content['title'] = self.get_argument('title')
                message_item['content']    = json.dumps(content)
                message_logic = messageLogic.messageLogic(self.application.db)
                mret = message_logic.send(message_item)
                logmsg += ' msg:%u' % (mret['retcode'], )
                #print message_logic.send(message_item)
            logging.info(logmsg)
        elif strType == 'post_cmt':
            #argument_dict = self.get_register_argument()
            #string_base64 = self.get_argument('code', '')
            #print string_base64
            logmsg = ''
            if checkin_ret['retcode'] != 0:
                ret = checkin_ret
                logging.warning('t:%s chk:%u' % (strType, ret['retcode'],))
            else:
                anti = antispam.antispam(mc.getInstance())
                anti_item = {}
                anti_item['uip']     = self.request.remote_ip
                anti_item['content'] = self.get_argument('reply')
                anti_item['user_id'] = checkin_ret['retbody']['user_id']
                anti_ret = anti.check_repeat(anti_item)
                if anti_ret['retcode'] != 0:
                    ret = anti_ret
                    logging.info('t:%s anti:%u uid:%u uip:%s' % (strType, ret['retcode'],\
                            anti_item['user_id'], anti_item['uip'],))
                else:
                    rplmsg = ''
                    content = {}
                    content['reply']     = self.get_argument('reply')
                    content['cmt']       = self.get_argument('cmt', '')
                    content['cmt_id']    = int(self.get_argument('cmt_id', 0))
                    content['cmt_uid']   = int(self.get_argument('cmt_uid', 0))
                    content['cmt_uname'] = self.get_argument('cmt_uname', '')
                    discuss_uid = int(self.get_argument('uid'))
                    if content['cmt'] == '' or  0 == content['cmt_uid'] or '' == content['cmt_uname']:
                        del content['cmt']
                        del content['cmt_id']
                        del content['cmt_uid']
                        del content['cmt_uname']
                    else:
                        # 发信通知评论作者
                        # $send_uname 对你在 $thread_id 中的评论: $cmt 进行了回复: $reply
                        message_item = {}
                        message_item['recv_uid']   = content['cmt_uid']
                        message_item['send_uid']   = checkin_ret['retbody']['user_id']
                        message_item['send_uname'] = checkin_ret['retbody']['user_name']
                        message_item['itype']      = T_DISCUSS_COMMENT_REPLY
                        message_item['creat_time'] = int(time.time())

                        content['id']   = int(self.get_argument('id'))
                        content['sex']  = checkin_ret['retbody']['sex']
                        message_item['content']    = json.dumps(content)
                        message_logic = messageLogic.messageLogic(self.application.db)
                        #print message_item
                        #print '-- send reply message', message_logic.send(message_item)
                        mret = message_logic.send(message_item)
                        rplmsg = 'msg:%u ruid:%u suid:%u itype:%u' % (mret['retcode'], message_item['recv_uid'],\
                                message_item['send_uid'], message_item['itype'], )

                    cmt_item = {}
                    # comment中content的格式
                    # 'reply'         -> 回复的内容
                    # 'quote_content' -> 被引用的内容
                    # 'quote_uid'     -> 被引用的用户id
                    # 'quote_uname'   -> 被引用的用户名
                    #['thread_id', 'comment_uid', 'comment_uname', 'creat_time', 'uip', 'content',]
                    cmt_item['content']       = content 
                    cmt_item['creat_time']    = int(time.time())
                    cmt_item['uip']           = self.request.remote_ip
                    cmt_item['age']           = int(time.strftime("%Y")) - checkin_ret['retbody']['birth_year']
                    cmt_item['sex']           = checkin_ret['retbody']['sex']
                    cmt_item['phone_type']    = self.get_argument('phone_type')
                    cmt_item['thread_id']     = int(self.get_argument('id'))
                    cmt_item['comment_uid']   = checkin_ret['retbody']['user_id']
                    cmt_item['comment_uname'] = checkin_ret['retbody']['user_name']
                    discuss_logic = discussLogic.discussLogic(self.application.db, mc.getInstance())
                    #bt = time.time()*1000000
                    ret = discuss_logic.add_comment(cmt_item)
                    logmsg = 't:%s r:%u id:%u cuid:%u cun:%s age:%u sex:%u' % (strType, ret['retcode'], \
                            cmt_item['thread_id'], cmt_item['comment_uid'], cmt_item['comment_uname'], \
                            cmt_item['age'], cmt_item['sex'],)
                    logmsg += ' ' + rplmsg
                    #print 'add comment', ret
                    #et = time.time()*1000000
                    #print "timecost: ", et-bt
                    # 给用户加活跃值
                    if 0 == ret['retcode']:
                        anti.set_content(anti_item)
                        user_logic.bonus4post_comment(checkin_ret['retbody']['user_id'])
                        if content.has_key('cmt_uid') and discuss_uid != content['cmt_uid']:
                            # 如果回复楼主的评论(discuss_uid == cmt_uid)就不发了，否则会收到一个评论+回复的消息，都是重复的内容
                            # 发信通知discuss作者
                            # $send_uname 对你在 $thread_id 中的评论: $quote_content 进行了回复: $reply
                            message_item = {}
                            message_item['recv_uid']   = discuss_uid
                            message_item['send_uid']   = checkin_ret['retbody']['user_id']
                            message_item['send_uname'] = checkin_ret['retbody']['user_name']
                            message_item['itype']      = T_DISCUSS_COMMENT
                            message_item['creat_time'] = int(time.time())

                            message_item['content']    = json.dumps(content)
                            message_logic = messageLogic.messageLogic(self.application.db)
                            #messageLogic.send(message_item)
                            #print message_item
                            #print '-- send comment', message_logic.send(message_item)
                            mret = message_logic.send(message_item)
                            msg = ' msg:%u ruid:%u suid:%u itype:%u' % (mret['retcode'], message_item['recv_uid'],\
                                    message_item['send_uid'], message_item['itype'], )
                            logmsg += msg
            logging.info(logmsg)
        else:
            # 404
            ret['retcode'] = E_METHOD_NOT_EXIST
            ret['message'] = 'method not exists'
            logging.warning('t:%s method not exists' % (strType,))
        #print ret
        self.write(json.dumps(ret))
